<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
          <el-form-item label="账单年度" prop="billYear">
            <el-input v-model="queryParams.billYear" placeholder="请输入账单年度" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="账单月份" prop="billMonth">
            <el-input v-model="queryParams.billMonth" placeholder="请输入账单月份" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="收支类型" prop="billRevenueExpenditureType">
            <el-select v-model="queryParams.billRevenueExpenditureType" placeholder="请选择收入支出类型" clearable>
              <el-option
                v-for="dict in crm_revenue_expenditure_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="收支方式" prop="billRevenueExpenditureWay">
            <el-select v-model="queryParams.billRevenueExpenditureWay" placeholder="请选择收入支出方式" clearable>
              <el-option
                v-for="dict in crm_revenue_expenditure_way"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="账单分类" prop="billClassification">
            <el-select v-model="queryParams.billClassification" placeholder="请选择账单分类" clearable>
              <el-option
                v-for="dict in crm_bill_classification"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
<!--          <el-form-item label="金额" prop="money">-->
<!--            <el-input v-model="queryParams.money" placeholder="请输入金额" clearable style="width: 240px" @keyup.enter="handleQuery" />-->
<!--          </el-form-item>-->
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['crmbill:billDetails:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['crmbill:billDetails:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['crmbill:billDetails:remove']">删除</el-button>
          </el-col>
<!--          <el-col :span="1.5">-->
<!--            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['crmbill:billDetails:export']">导出</el-button>-->
<!--          </el-col>-->
          <el-col :span="1.5">
            <el-dropdown class="mt-[1px]">
              <el-button plain type="info">
                更多
                <el-icon class="el-icon--right"><arrow-down /></el-icon
                ></el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="importTemplate" icon="Download">下载模板</el-dropdown-item>
                  <el-dropdown-item @click="handleImport" icon="Top"> 导入数据</el-dropdown-item>
                  <el-dropdown-item @click="handleExport" icon="Download"> 导出数据</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="billDetailsList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="账单id" align="center" prop="billId" v-if="false" />
        <el-table-column label="年度" align="center" prop="billYear" v-if="false"/>
        <el-table-column label="月份" align="center" prop="billMonth" v-if="false"/>
        <el-table-column label="日期" align="center" prop="billDate" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.billDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="收支类型" align="center" prop="billRevenueExpenditureType" width="90">
          <template #default="scope">
            <dict-tag :options="crm_revenue_expenditure_type" :value="scope.row.billRevenueExpenditureType"/>
          </template>
        </el-table-column>
        <el-table-column label="收支方式" align="center" prop="billRevenueExpenditureWay" width="150">
          <template #default="scope">
            <dict-tag :options="crm_revenue_expenditure_way" :value="scope.row.billRevenueExpenditureWay"/>
          </template>
        </el-table-column>
        <el-table-column label="账单分类" align="center" prop="billClassification" width="120">
          <template #default="scope">
            <dict-tag :options="crm_bill_classification" :value="scope.row.billClassification"/>
          </template>
        </el-table-column>
        <el-table-column label="金额" align="center" prop="money" width="100"/>
        <el-table-column label="事项内容" align="center" prop="billItemContent" width="300"/>
        <el-table-column label="备注" align="center" prop="remarks" width="350"/>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['crmbill:billDetails:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['crmbill:billDetails:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>
    <!-- 添加或修改账单明细对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="800px" append-to-body>
      <el-form ref="billDetailsFormRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="账单年度" prop="billYear" v-if=false>
          <el-input v-model="form.billYear" placeholder="请输入账单年度" />
        </el-form-item>
        <el-form-item label="账单月份" prop="billMonth" v-if="false">
          <el-input v-model="form.billMonth" placeholder="请输入账单月份" />
        </el-form-item>


        <el-row>
          <el-col :span="12">
            <el-form-item label="日期" prop="billDate">
              <el-date-picker clearable
                              v-model="form.billDate"
                              type="datetime"
                              value-format="YYYY-MM-DD HH:mm:ss"
                              placeholder="请选择日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="收入支出类型" prop="billRevenueExpenditureType">
              <el-select v-model="form.billRevenueExpenditureType" filterable clearable placeholder="请选择收入支出类型">
                <el-option
                  v-for="dict in crm_revenue_expenditure_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>


        <el-row>
          <el-col :span="12">
            <el-form-item label="收入支出方式" prop="billRevenueExpenditureWay">
              <el-select v-model="form.billRevenueExpenditureWay" filterable clearable  placeholder="请选择收入支出方式">
                <el-option
                  v-for="dict in crm_revenue_expenditure_way"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="账单分类" prop="billClassification">
              <el-select v-model="form.billClassification" filterable clearable  placeholder="请选择账单分类">
                <el-option
                  v-for="dict in crm_bill_classification"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="金额" prop="money">
          <el-input v-model="form.money" placeholder="请输入金额" />
        </el-form-item>

        <el-row>
          <el-col :span="24">
            <el-form-item label="事项内容">
              <el-input v-model="form.billItemContent" type="textarea" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input v-model="form.remarks" type="textarea" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>


    <!-- 账单明细导入对话框 -->
    <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
      <el-upload
        ref="uploadRef"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <el-icon class="el-icon--upload">
          <i-ep-upload-filled />
        </el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="text-center el-upload__tip">
            <div class="el-upload__tip"><el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据</div>
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup name="BillDetails" lang="ts">
import { listBillDetails, getBillDetails, delBillDetails, addBillDetails, updateBillDetails } from '@/api/crmbill/billDetails';
import { BillDetailsVO, BillDetailsQuery, BillDetailsForm } from '@/api/crmbill/billDetails/types';
import { globalHeaders } from "@/utils/request";

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { crm_revenue_expenditure_type, crm_bill_classification, crm_revenue_expenditure_way } = toRefs<any>(proxy?.useDict('crm_revenue_expenditure_type', 'crm_bill_classification', 'crm_revenue_expenditure_way'));

const billDetailsList = ref<BillDetailsVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const billDetailsFormRef = ref<ElFormInstance>();
const uploadRef = ref<ElUploadInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

/*** 用户导入参数 */
const upload = reactive<ImportOption>({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: globalHeaders(),
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/crmbill/billDetails/importData"
})

const initFormData: BillDetailsForm = {
  billId: undefined,
  billYear: undefined,
  billMonth: undefined,
  billDate: undefined,
  billRevenueExpenditureType: undefined,
  billRevenueExpenditureWay: undefined,
  billClassification: undefined,
  billItemContent: undefined,
  money: undefined,
  remarks: undefined,
}
const data = reactive<PageData<BillDetailsForm, BillDetailsQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 20,
    billYear: undefined,
    billMonth: undefined,
    billDate: undefined,
    billRevenueExpenditureType: undefined,
    billRevenueExpenditureWay: undefined,
    billClassification: undefined,
    billItemContent: undefined,
    money: undefined,
    remarks: undefined,
    params: {
    }
  },
  rules: {
    billId: [
      { required: true, message: "账单id不能为空", trigger: "blur" }
    ],
    billYear: [
      { required: true, message: "账单年度不能为空", trigger: "blur" }
    ],
    billMonth: [
      { required: true, message: "账单月份不能为空", trigger: "blur" }
    ],
    billDate: [
      { required: true, message: "日期不能为空", trigger: "blur" }
    ],
    billRevenueExpenditureType: [
      { required: true, message: "收入支出类型不能为空", trigger: "change" }
    ],
    billRevenueExpenditureWay: [
      { required: true, message: "收入支出方式不能为空", trigger: "change" }
    ],
    billClassification: [
      { required: true, message: "账单分类不能为空", trigger: "change" }
    ],
    billItemContent: [
      { required: true, message: "事项内容不能为空", trigger: "blur" }
    ],
    money: [
      { required: true, message: "金额不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询账单明细列表 */
const getList = async () => {
  loading.value = true;
  const res = await listBillDetails(queryParams.value);
  billDetailsList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  billDetailsFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: BillDetailsVO[]) => {
  ids.value = selection.map(item => item.billId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加账单明细";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: BillDetailsVO) => {
  reset();
  const _billId = row?.billId || ids.value[0]
  const res = await getBillDetails(_billId);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改账单明细";
}

/** 提交按钮 */
const submitForm = () => {
  billDetailsFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.billId) {
        await updateBillDetails(form.value).finally(() =>  buttonLoading.value = false);
      } else {
        await addBillDetails(form.value).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("修改成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: BillDetailsVO) => {
  const _billIds = row?.billId || ids.value;
  await proxy?.$modal.confirm('是否确认删除账单明细编号为"' + _billIds + '"的数据项？').finally(() => loading.value = false);
  await delBillDetails(_billIds);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('crmbill/billDetails/export', {
    ...queryParams.value
  }, `billDetails_${new Date().getTime()}.xlsx`)
}

/** 下载模板操作 */
const importTemplate = () => {
  proxy?.download("crmbill/billDetails/importTemplate", {
  }, `crm_bill_template_${new Date().getTime()}.xlsx`);
}

/** 导入按钮操作 */
const handleImport = () => {
  upload.title = "账单明细";
  upload.open = true;
}

/**文件上传中处理 */
const handleFileUploadProgress = () => {
  upload.isUploading = true;
}
/** 文件上传成功处理 */
const handleFileSuccess = (response: any, file: UploadFile) => {
  upload.open = false;
  upload.isUploading = false;
  uploadRef.value?.handleRemove(file);
  ElMessageBox.alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
  getList();
}

/** 提交上传文件 */
function submitFileForm() {
  uploadRef.value?.submit();
}


onMounted(() => {
  getList();
});
</script>
